package com.haojiang.mh.ui.activity

import android.animation.AnimatorInflater
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.utils.ActManager
import com.haojiang.mh.utils.MUtil
import kotlinx.android.synthetic.main.activity_config_wifi.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 配置WiFi
 *
 * Created by ZapFive on 2019-05-26.
 *
 * wuzhuang@mirahome.me
 */
class ConfigWiFiActivity : BaseActivity() {

    private var configTimeoutJob: Job? = null
    private var delaySendJob: Job? = null
    private var count: Int = 0

    override fun getLayoutId() = R.layout.activity_config_wifi

    override fun getTitleName() = ""

    override fun initActivity() {
//        BleHandle.instance.sendWifiInfo()
        delayHandleSend()
    }

    override fun initView() {
        val animator = AnimatorInflater.loadAnimator(context, R.animator.rotate_config_wifi)
        animator.setTarget(aiv_rotate_img)
        animator.start()

        initTimeMachine()
    }


    private fun delayHandleSend() {
        MUtil.cancelJob(delaySendJob)

        delaySendJob = GlobalScope.launch {
            while (count < 3) {
                BleHandle.instance.sendWifiInfo()
                delay(1_000L)
                count++
            }
        }
    }


    override fun onDestroy() {
        MUtil.cancelJob(configTimeoutJob)
        MUtil.cancelJob(delaySendJob)
        super.onDestroy()
    }

    /**
     * 开始30秒超时线程
     */
    private fun initTimeMachine() {
        MUtil.cancelJob(configTimeoutJob)
        configTimeoutJob = GlobalScope.launch {
            delay(30_000L)
            withContext(Dispatchers.Main) {
                showToast(R.string.txt_config_time_out)
                context.finish()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveEvent(event: OneEvent) {
        when (event.type) {
            Const.SET_WIFI_EVENT -> {
                // app 收到设备联网消息后，发送回执
                BleHandle.instance.sendCallBackInfo()
                //0:成功 1:配网超时 2:联网失败 3:JSON 解析错误 4:SSID 为空
                when (event.getIntValue()) {
                    0 -> redirectWithExtraAndFinish(Const.SET_WIFI_SUCCESS, CommonSuccessActivity::class.java)
                    else -> redirectWithExtraAndFinish(3, SearchWiFiFailActivity::class.java)
                }
            }
            Const.DISCONNECT_DEVICE -> {//设备掉线
                ActManager.redirectToBottomActivity()
                context.finish()
            }
            Const.RECEIVE_CALLBACK -> { // 1秒重试
                MUtil.cancelJob(delaySendJob)
            }
        }
    }
}